//
//  FishMapListTableViewController.m
//  MyFishHelper
//
//  Created by EmberWei on 2018/6/27.
//  Copyright © 2018年 EmberWei. All rights reserved.
//

#import "FishMapListTableViewController.h"
#import "FishingCell.h"
#import "FishinResultTableViewController.h"

@interface FishMapListTableViewController ()
@property (nonatomic,strong) NSArray<FishMap*> *fishMaps;
@property (nonatomic,strong) NSMutableArray<FishingAwardItem*> *fishAwards;
@end

@implementation FishMapListTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self reqeust];
    self.title = @"选择渔场";
}

-(void)showLoginAlert
{
    RAlertView *alert = [[RAlertView alloc] initWithStyle:ConfirmAlert];
    alert.headerTitleLabel.text = @"Token过期";
    alert.theme = RGB16(0X1abc9c);
    NSMutableString *string = [[NSMutableString alloc]initWithString:@"您在其他地方登录,请重新登录"];
    alert.contentTextLabel.attributedText = [TextHelper attributedStringForString:string lineSpacing:5];;
    [alert.confirmButton setTitle:@"好的" forState:UIControlStateNormal];
    WEAK(self)
    alert.confirm = ^(){
        STRONG(self)
        [self dismissViewControllerAnimated:YES completion:nil];
    };
}

-(void)reqeust
{
    WEAK(self)
    [Api apiFishMap:^(ResponseFishMap *result, NSError *error) {
        STRONG(self)
        if (error) {
            [MFHUDManager showError:@"请检查网络,稍后再试"];
            return;
        }
        if (![result.code isEqualToString:@"0"]) {
            if ([result.code isEqualToString:@"20000"]) {
                [self showLoginAlert];
                return;
            }
            [MFHUDManager showError:result.msg];
            return;
        }
        if ([result.lists count] == 0) {
            [MFHUDManager showError:@"钓鱼渔场列表为空"];
            return;
        }
        self.fishMaps = result.lists;
        [self.tableView reloadData];
    }];
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [self.fishMaps count];
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    FishMap *map = self.fishMaps[indexPath.row];
    FishingCell *cell = [tableView dequeueReusableCellWithIdentifier:@"FishingCell" forIndexPath:indexPath];
    cell.nameLabel.text = map.map_name;
    [cell.fishHead sd_setImageWithURL:[NSURL URLWithString:map.icon]];
    [cell.fishStoneIcon sd_setImageWithURL:[NSURL URLWithString:map.stosh_img]];
    cell.itemLabel.text = FORMAT(@"鱼饵数: %@",map.my_num);
    NSInteger num = [map.my_num integerValue];
    
    WEAK(self)
    WEAK(cell)
    cell.block = ^(NSInteger times) {
        STRONG(self)
        STRONG(cell)
        if (num < times) {
            [MFHUDManager showError:@"鱼饵不足"];
            return;
        };
        self.fishAwards = [[NSMutableArray alloc]init];
        [self requestFishing:map.map_id succ:cell.isSuceess times:times];
    };
    return cell;
}

-(void)requestFishing:(NSNumber*)map_id succ:(BOOL)isSucc times:(NSInteger)times
{
    WEAK(self)
    __block NSInteger cnt = times;
    [MFHUDManager showLoading:@"钓鱼中...."];
    for (int i = 0;  i < times; i++ ) {
        NSNumber *type = isSucc ? @(1) : @(0);
        [Api apiFisingWithSucc:type mapid:map_id handler:^(ResponseFishAward *result, NSError *error) {
            STRONG(self)
            if (error) {
                [MFHUDManager showError:@"请检查网络,稍后再试"];
                return;
            }
            if (![result.code isEqualToString:@"0"]) {
                [MFHUDManager showError:result.msg];
                return;
            }
            cnt--;
            FishingAwardItem *award = result.data.firstObject;
            if (award) {
                [self.fishAwards addObject:award];
            }
            if (cnt == 0) {
                NSMutableString *string = [[NSMutableString alloc]initWithString:@"一键钓鱼成功!"];
                [MFHUDManager showSuccess:string];
                [self reqeust];
                NSMutableArray *array = [self resultTableArrayWithPercent:[self resultTableArray]];
                [self pushToVC:array];
            }
        }];
    }
}

-(NSMutableArray*)resultTableArray
{
    NSMutableArray *resArr = [[NSMutableArray alloc]init];
  
    for (FishingAwardItem *award in self.fishAwards) {
        NSString *num =  award.item_num;
        
        BOOL isSame = [self isHaveSame:award fishAwards:resArr];
        if (!isSame) {
            award.item_times = 1;
            award.item_total = [num integerValue];
            [resArr addObject:award];
        }
        else
        {
            FishingAwardItem *same = [self getSame:award fishAwards:resArr];
            same.item_times += 1;
            same.item_total += [num integerValue];
        }
    }
    return resArr;
}

-(NSMutableArray*)resultTableArrayWithPercent:(NSMutableArray*)oldFishAwards
{
    NSInteger count = [self.fishAwards count];
    NSMutableArray *resArr = [[NSMutableArray alloc]init];
    for (FishingAwardItem *award in oldFishAwards) {
        CGFloat percentf = ((award.item_times *1.0f) / count) * 100.f;
        NSString *percent = FORMAT(@"%0.2f%%",percentf);
        award.percent = percent;
        [resArr addObject:award];
    }
    return resArr;
}

-(BOOL)isHaveSame:(FishingAwardItem*)newAward fishAwards:(NSMutableArray<FishingAwardItem*>*)fishAwards {
    NSString *newImg = newAward.img;
    for (FishingAwardItem *award in fishAwards) {
        if ([newImg isEqualToString:award.img]) {
            return YES;
        }
    }
    return NO;
}

-(FishingAwardItem*)getSame:(FishingAwardItem*)newAward fishAwards:(NSMutableArray<FishingAwardItem*>*)fishAwards {
    NSString *newImg = newAward.img;
    for (FishingAwardItem *award in fishAwards) {
        if ([newImg isEqualToString:award.img]) {
            return award;
        }
    }
    return nil;
}

-(void)pushToVC:(NSMutableArray*)array
{
    FishinResultTableViewController *vc = [[UIStoryboard storyboardWithName:@"Home" bundle:nil] instantiateViewControllerWithIdentifier:@"FishinResultTableViewController"];
    vc.items = array;
    [self.navigationController pushViewController:vc animated:YES];
}


@end
